package com.swsc.xapp.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;

public class JacksonUtils {
    private static final com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();


    public static String toJson(Object object) {
        try {
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            android.util.Log.e("JSON转换", e.getMessage());
        }
        return null;
    }

    public static <T> T fromJson(String json, Class<T> clazz){
        try {
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            android.util.Log.e("JSON转换", e.getMessage());
        }
        return null;
    }

    public static <T> T fromJson2J(String json, TypeReference<T> typeRef){
        try {
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return objectMapper.readerFor(typeRef).readValue(json);
        } catch (JsonProcessingException e) {
            android.util.Log.e("JSON转换", e.getMessage());
            NativeJSUtils.writeString2File(ConstantUils.DIR_BASE.concat("Log_" + System.currentTimeMillis() + ".txt"), e.getMessage());
        }
        return null;
    }


    private JacksonUtils(){}
}
